package com.wei.utils.spring;

import com.wei.utils.Assert;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

//需要在applicationContext.xml配置一下,否则是不会注入进来的
public class SpringApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public static <T> T getBean(String beanName){
        Assert.notNull(applicationContext,"%s","ApplicationContext对象注入失败!");
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<?> clazz){
        Assert.notNull(applicationContext,"%s","ApplicationContext对象注入失败!");
        return (T) applicationContext.getBean(clazz);
    }
}
